﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;

namespace SecureCookie.Implementation.Helper
{
    /// <summary>
    /// Helper class with extension methods for <see cref="Exception"/>
    /// </summary>
    public static class ExceptionHelper
    {
        /// <summary>
        /// Represents an <see cref="Exception"/> as a string, containing also all inner exceptions
        /// </summary>
        /// <param name="exception">The exception that should be represented as a string</param>
        /// <returns>The exception represented as a string</returns>
        public static string RepresentAsStringRecursively(this Exception exception)
        {
            if (exception.InnerException == null)
                return exception.RepresentAsString();

            var builder = new StringBuilder(exception.RepresentAsString());
            var inner = exception.InnerException;
            while (inner != null)
            {
                builder.AppendLine("Inner Exception : ");
                builder.Append(inner.RepresentAsString());
                inner = inner.InnerException;
            }
            return builder.ToString();
        }

        private static string RepresentAsString(this Exception exception)
        {
            return string.Format(CultureInfo.InvariantCulture, "Exception with message [{0}] and stacktrace [{1}] and data [{2}]",
                exception.Message, exception.StackTrace, RepresentAsString(exception.Data));
        }
        private static string RepresentAsString(System.Collections.IDictionary dictionary)
        {
            var builder = new StringBuilder();
            foreach (var key in dictionary.Keys)
            {
                builder.AppendLine(string.Format(CultureInfo.InvariantCulture, "{0} || {1}", key, dictionary[key]));
            }
            return builder.ToString();
        }
    }
}
